package com.meng.function.tpm.p.small;

import com.meng.function.gui.MapDeleteRunnable;
import com.meng.function.gui.TpmGUI;
import com.meng.function.tpm.p.pojo.AddressPojo;
import com.meng.function.tpm.p.util.Local;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import net.kyori.adventure.text.event.ClickEvent;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;

import java.util.HashMap;
import java.util.List;

public class TpmPShare {

    public boolean onCommand(Player player, String addressName, Player toPlayer) {
        if (TpmGUI.mapDeleteRunnableList.size() > 0 && TpmGUI.mapDeleteRunnableList.get(0).state != 0){
            TpmGUI.mapDeleteRunnableList.get(0).run();
        }
        AddressPojo addressPojo = new AddressPojo();
        addressPojo.setAddressName(addressName);
        if (toPlayer != null) {
            toPlayer.sendMessage(player.getName() + "给您分享了一个位置");
            addressPojo.setIsShare(player.getName());
            new Local().upData(addressPojo,player.getName());
            sendMsgPlayer(player, addressName, toPlayer);
        } else {
            addressPojo.setIsShare("all");
            new Local().upData(addressPojo,player.getName());
            for (Player onlinePlayer : Bukkit.getOnlinePlayers()) {
                if (onlinePlayer.getName().equals(player.getName())){
                    player.sendMessage("将地址:"+ addressName +"分享成功");
                    continue;
                }
                onlinePlayer.sendMessage(player.getName() + "给您分享了一个位置");
                sendMsgPlayer(player, addressName, onlinePlayer);
            }
        }
        return true;
    }

    private void sendMsgPlayer(Player player, String addressName, Player onlinePlayer) {
        List<HashMap<String, Object>> allAddress = new Local().getAllAddress(player.getName());
        for (HashMap<String, Object> address : allAddress) {
            String addressNamePlayer = (String) address.get("addressName");
            if (addressNamePlayer.equals(addressName)) {
                TextComponent tpmPAdd = Component.text("位置名称为:" + addressNamePlayer +
                                "坐标: x: " + address.get("x") + " y: " + address.get("y") + " z: " + address.get("z"))
                        .clickEvent(ClickEvent.runCommand("/tpm-p share-add " + player.getName() + " " + addressNamePlayer)
                        );
                onlinePlayer.sendMessage(tpmPAdd);
                break;
            }
        }
    }
}
